from typing import List, Dict, Any, Optional
from datetime import datetime
from pathlib import Path

from src.models.content import Content, MediaFile
from src.infrastructure.database import DatabaseManager

class ContentService:
    def __init__(self, db_manager: DatabaseManager):
        self.db_manager = db_manager
        
    async def save_content(self, 
                          platform: str,
                          content_data: Dict[str, Any],
                          media_files: List[Dict[str, str]] = None) -> Content:
        """保存内容和相关媒体文件"""
        with self.db_manager.get_session() as session:
            # 创建内容记录
            content = Content(
                platform=platform,
                content_type=content_data['metadata'].content_type,
                url=content_data.get('url', ''),
                title=content_data.get('title', ''),
                text=content_data.get('text', ''),
                author=content_data['metadata'].author,
                publish_time=content_data['metadata'].publish_time,
                likes=content_data['metadata'].likes,
                comments=content_data['metadata'].comments,
                collections=content_data['metadata'].collections
            )
            session.add(content)
            session.flush()  # 获取content.id
            
            # 保存媒体文件记录
            if media_files:
                for media in media_files:
                    media_file = MediaFile(
                        content_id=content.id,
                        file_type=media['type'],
                        original_url=media['original_url'],
                        local_path=media['local_path'],
                        file_size=Path(media['local_path']).stat().st_size
                    )
                    session.add(media_file)
            
            return content
            
    async def get_content(self, 
                         platform: str = None,
                         author: str = None,
                         start_time: datetime = None,
                         end_time: datetime = None,
                         **filters) -> List[Content]:
        """查询内容"""
        with self.db_manager.get_session() as session:
            query = session.query(Content)
            
            if platform:
                query = query.filter(Content.platform == platform)
            if author:
                query = query.filter(Content.author == author)
            if start_time:
                query = query.filter(Content.publish_time >= start_time)
            if end_time:
                query = query.filter(Content.publish_time <= end_time)
                
            # 应用其他过滤条件
            for key, value in filters.items():
                if hasattr(Content, key):
                    query = query.filter(getattr(Content, key) == value)
                    
            return query.all() 